package 多线程案例;
//实现阻塞队列
class MyBlockingQueue{

    Object A = new Object();
    int[] elems = null;
    int right ;
    int tail ;
    int usedSize;
    MyBlockingQueue(int capacity){
        elems = new int[capacity];
    }

    //注意锁的位置

    //放入操作
    public void put(int elem) throws InterruptedException {
        synchronized (A){
            //如果满，不能放出
            while (usedSize>=elems.length){
                A.wait();
            }
            //没有满，正常放入
            elems[tail++] = elem;
            if(tail>=elems.length){
                tail = 0;
            }
            usedSize++;
            A.notify();
        }

    }
    public int take() throws InterruptedException {
        synchronized (A){
            //如果为空，不能取出
            while (usedSize == 0){
                A.wait();
            }
            //不为空，正常取出
            int elem = elems[right++];
            //另一种写法
            right = right%elems.length;
            usedSize--;
            A.notify();
            return elem;
        }
    }

}
public class Demo_4 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue m  =new MyBlockingQueue(100);
        m.put(1);
        System.out.println(m.take());
    }

}
